import { Component, OnInit, Input } from '@angular/core';
import { TipService, ModalTipService, ModalService ,HttpService} from 'itcloud-plugin';
import { GetPathService } from '../../get-path.service';
import { Router} from '@angular/router'; //导入router服务
import { AnnexClass } from './annex-class';
@Component({
  selector: 'app-reply-notice',
  templateUrl: './reply-notice.component.html',
  styleUrls: ['./reply-notice.component.css']
})
export class ReplyNoticeComponent implements OnInit {

  @Input() handler;
  @Input() data;

  replyContent:string;

  annex: AnnexClass[] = [];
  public viewNotice:any={};
  public viewNoticeFiles:any={};
  public  uploadId:any=[];
  public  infoName:string;
  constructor(private http: HttpService,
              private tipService: TipService,
              private GetPathService: GetPathService,
              private router: Router
  ) { }

  /*取消点击关闭*/
  closeDrawer() {
    this.handler&& this.handler();
  }

  /*已阅*/
  doneNotice(){
    this.http.getData({
      url: this.GetPathService.AjaxPath.bulletinServer+`/mineTodo/udateStatus?id=${this.viewNotice.todoId}&type=${this.viewNotice.infoType}&status=${this.viewNotice.todoStatus}`,
    }).subscribe(res => {
      this.closeDrawer();
      this.router.navigateByUrl("/done");
    }, err => {
      console.log(err.returnMessage)
    });
  }
  /*保存saveType=0，发送回复保存saveType=1接口*/
  saveNotice(saveType){
    let  fileIdOne:string='';
    let  FileIdTwo:string='';
    let  finallyFileID:string='';
        /*上传附件id*/
      for(let i=0; i<this.annex.length; i++){
          fileIdOne+=`${this.annex[i].id},`;
      }
      /*已上传附件的id*/
      for(let i=0;i<this.viewNoticeFiles.todoAtts.length;i++){
          FileIdTwo+=`${this.viewNoticeFiles.todoAtts[i].id},`;
      }
      for(let k=0;k<(fileIdOne+FileIdTwo).length;k++){
          finallyFileID=(fileIdOne+FileIdTwo).substr(0,k);
      }
      if(this.replyContent==null){
          this.replyContent="";
      }
    const objSave={};
    this.http.getData({
      url: this.GetPathService.AjaxPath.bulletinServer+`/mineTodo/replyInfoById?replyContent=${this.replyContent}&id=${ this.viewNotice.todoId }&attachmentIds=${finallyFileID}&saveType=${saveType}`,
      objSave,
    }).subscribe(res => {
      this.tipService.show({
        type: 'success',
        title: res['returnMessage']
      });
      this.closeDrawer();
      this.router.navigateByUrl("/todu");
    }, err => {
      this.tipService.show({
        type: 'error',
        title: err.returnMessage
      });
    });
  }
  /*
  获取列表公告数据
  * */
  /*${this.data.id}*/
  requestData() {
    this.http.getData({
      url: this.GetPathService.AjaxPath.bulletinServer+`/mineTodo/getMineTodoById?id=${this.data.infoTodoId}`,
    }).subscribe(res => {
        this.viewNotice=res['bean'].info;
        this.viewNoticeFiles=res['bean'];
        this.replyContent=this.viewNotice.todoReplyContent;
        if(this.viewNotice.infoType==0){
            this.infoName=`关于${this.viewNotice.infoName}的公告通知`;
        }else if(this.viewNotice.infoType==1){
            this.infoName=`关于${this.viewNotice.infoName}的信息交流`;
        }

    }, err => {
      console.log(err.returnMessage)
    });
  }




 /*附件上传*/
  fileName: any;
  content: string;      //内容；
  type='公告通知';
  message='是';

  options = {
    url: this.GetPathService.AjaxPath.bulletinServer+'/attachment/addFile',
    method: 'POST',
    itemAlias: 'file',
    autoUpload: true,
    encodeFilename: true,
    selfCheck: (file) => { // 自己的校验规则，请return true或者false
      //return this.myCheckFile(file);
      return true;
    }
  };
  /**
   * 修改上传文件回调
   * @param data
   */
  fileChangeEvent(data) {
    this.fileName = data['file'].name;
  }
  /**
   * 文件上传成功回调
   * @param data
   */
  fileUploadSuccess(res) {
    const data = JSON.parse(res.response);
    data['result'].fileOriginName = this.fileName;

    const uoloadDate: AnnexClass = {
      attachName: data['result'].fileOriginName,
      attachUrl: data['result'].filePath,
      attachSize: data['result'].size,
      id: data['result'].id
    };
    this.annex.push(uoloadDate);
    this.tipService.show({ type: 'success', title: '上传成功！' });


  }

  /**
   * 文件上传失败回调
   * @param data
   */
  fileUploadError(ev) {
    console.log(ev);
    if (ev === 'overSize') {
      this.tipService.show({
        type: 'error',
        title: '上传文件超出最大限制！'
      });
    } else if (ev === 'errorType') {
      this.tipService.show({
        type: 'error',
        title: '上传文件格式不支持！'
      });
    } else {
      this.tipService.show({
        type: 'error',
        title: '上传文件失败！'
      });
    }
  }
  /*
   * 删除上传附件
   * */
  delFiles(ev, list: Array<any>) {
    for (let i = list.length - 1; i >= 0; i--) {
      if (list[i].id === ev) {
        list.splice(i, 1);
        break;
      }
    }
  }


 /***
  * 时间转换
  *
  *
  * */
 timeStamp(timestamp){
     let Y,M,D,h,m,s;
     let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
     //var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
     Y = date.getFullYear() + '-';
     M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
     D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
     h = (date.getHours() < 10 ? '0'+ date.getHours() : date.getHours()) + ':';
     m = (date.getMinutes() < 10 ? '0'+ date.getMinutes() : date.getMinutes()) + ':';
     s = (date.getSeconds()< 10 ? '0'+ date.getSeconds() : date.getSeconds());
     return Y+M+D+h+m+s;
 }
  /*附件大小转化*/
  conver(limit){
  let size = "";
  if( limit < 0.1 * 1024 ){ //如果小于0.1KB转化成B
    size = limit.toFixed(2) + "B";
  }else if(limit < 0.1 * 1024 * 1024 ){//如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + "KB";
  }else if(limit < 0.1 * 1024 * 1024 * 1024){ //如果小于0.1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + "MB";
  }else{ //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  }

  let sizestr = size + "";
  let len = sizestr.indexOf("\.");
  let dec = sizestr.substr(len + 1, 2);
  if(dec == "00"){//当小数点后为00时 去掉小数部分
    return sizestr.substring(0,len) + sizestr.substr(len + 3,2);
  }
  return sizestr;
}


  ngOnInit() {
      //this.getHeaderr();
      this.requestData();

    //console.log(this.data)
  }

}
